<template>
  <div class="full-height page-content bg-white content padding-20">
    <div class="font-16 text-weight-bold" style="padding-bottom: 8px">说明：</div>
    <div class="font-14" style="padding-bottom: 8px">1、logo整体尺寸建议150*40px，logo图标建议36*36px；logo图片背景透明，png格式显示效果最佳；logo图片大小不能超过2M；</div>
    <!-- 什么蜜汁制杖操作 -->
    <div class="font-14" style="padding-bottom: 8px">2、点击“+”图标可选择图片进行上传；如需重新上传可将鼠标移到图片处点击“删除”图标清除图片，清除后可重新上传。</div>
    <q-form @submit="submit" greedy class="dialog-content form-inline block" style="padding-right: 0;padding-left: 0" >
      <q-icon
        v-if="!!logoUrl"
        size="24px"
        class="del"
        name="iconfont icontubiao-52"
        @click="delImg"
        style="font-size: 24px !important;color: #D3D3D3;"
      />
      <div class="photo-box">
        <q-img
          class="photo"
          fit="contain"
          :src="logoUrl"
          spinner-color="white"
        >
          <div
            v-if="!logoUrl"
            style="height: 100%; width: 100%; background: #fff;"
          />
          <q-btn
            class="upload-btn"
            unelevated
            @click="_onUploadPhotoClick"
            :class="{ 'dashed-border': !logoUrl }"
          >
            <q-icon
              v-if="!logoUrl"
              size="24px"
              class="photo"
              name="iconfont icontubiao-56"
              style="font-size: 24px !important;color: #D3D3D3;"
            />
          </q-btn>
        </q-img>
        <input
          ref="fileInput"
          type="file"
          style="display: none;"
          accept="image/jpg, image/jpeg, image/png"
          @input="onPhotoFileSelected"
        />
      </div>
      <q-btn unelevated label="确认" color="primary" type="submit" style="margin-left: 102px"/>

    </q-form>
  </div>
</template>

<script>
import { uploadFlie } from '../../boot/template/template-upload'
import { getCustomerSet, setCustomerSet } from '../../boot/system/customer-set'
import { mapActions, mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  name: 'set-logo',
  data () {
    return {
      fileName: '',
      logoUrl: '',
      systemLogo: null
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  created () {
    this.getCustomerSet()
  },
  methods: {
    delImg () {
      this.$refs.fileInput.value = null
      this.logoUrl = ''
    },
    getCustomerSet () {
      this.fileName = ''
      getCustomerSet().then(res => {
        const systemLogo = _.isNil(res.systemLogo) ? null : res.systemLogo
        this.systemLogo = systemLogo
        this.logoUrl = systemLogo
      })
      this.$nextTick(() => {
        this.$refs.fileInput.value = null
      })
    },
    // 上传照片
    _onUploadPhotoClick: function () {
      // 触发文件选择
      this.$refs.fileInput.dispatchEvent(new MouseEvent('click'))
    },
    // 选择照片
    onPhotoFileSelected (e) {
      let file = this.$refs.fileInput.files[0]
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.logoUrl = reader.result
      }
    },
    submit () {
      if (this.systemLogo === this.logoUrl) {
        return
      }
      if (this.logoUrl === '') {
        this.setCustomerSet('')
      } else {
        let file = this.$refs.fileInput.files
        if (!this.$utils.fileTypeHoldUp(file[0].name, ['.jpg', '.jpeg', '.png'])) {
          return
        }
        let fileSize = file[0].size
        let fileMaxSize = 1024 * 1024 * 2
        if (fileSize <= fileMaxSize) {
          const path = this.CommonConfig.ossFilePath.logoImagesDir
          let res = this.$getUploadPath(file, path)
          this.fileName = res.fileNameNew
          this.onSubscribe()
          this.uploadFlie(res.uploadPath, file[0], res.fileNameNew)
        } else {
          this.$message.warning('文件大小不能超过2M')
        }
      }
    },
    // 上传文件
    uploadFlie (uploadPath, files, fileNameNew) {
      uploadFlie(uploadPath, files, fileNameNew).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('上传失败，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(() => {
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.fileName}`, this.onImgMessageArrived, { id: `${this.fileName}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.fileName}`)
      this.$q.loading.hide()
    },
    onImgMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.fileName) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('上传失败，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      this.closeUbscribeTopic()
      this.setCustomerSet(msg.data)
    },
    setCustomerSet (imgUrl) {
      const params = {
        systemLogo: imgUrl
      }
      setCustomerSet(params).then(() => {
        this.getCustomerSet()
        this.$message.success('保存成功！')
        this.saveCustomerSet()
      })
    },
    ...mapActions([
      'saveCustomerSet'
    ])
  }
}
</script>

<style scoped lang="stylus">
  .photo-box {
    margin-bottom 20px
    margin-left 50px
    margin-top 8px
    display flex
    flex-direction column
    align-items center
    border 1px dashed #D3D3D3

    border-radius 6px
    width 204px
    justify-content space-between

    .photo {
      height 80px
      width 200px
      border-radius 6px
      >>>.q-img__image{
        background-size contain !important
      }
      .upload-btn {
        height 100%
        width 100%
      }
    }
  }
  .del{
    cursor pointer
    position absolute
    left 240px
    z-index 11
  }
</style>
